Javascript - slice vs splice


*slice:
選取start index ~ end index的範圍,複製原始陣列切割出新陣列,不影響原始陣列。
slice(start, end)

let numbers = [1, 2, 3, 4, 5]

let slicedItems = numbers.slice(1, 2)
console.log(slicedItems) // [2]
console.log(numbers); // [1, 2, 3, 4, 5]

*splice:
給予start index + delete count,從原始陣列切割部分陣列,成為新陣列,影響原始陣列。
splice(start, deleteCount, item1, item2...)

let numbers = [1, 2, 3, 4, 5]

let deletedItems = numbers.splice(1, 2)
console.log(deletedItems) // [2, 3]
console.log(numbers); // [1, 4, 5]

numbers.splice(1, 0, 6, 7)
console.log(numbers); // 1, 6, 7, 4, 5]






你可能感興趣的文章

Command Line

Command Line

Docker 安裝 MySQL & 資料庫匯出/匯入 & 匯入中文亂碼解決方法

Docker 安裝 MySQL & 資料庫匯出/匯入 & 匯入中文亂碼解決方法

convert row to column

convert row to column






留言討論